/**
 * 封装 WebSocket
 */
import {useMessage} from 'naive-ui'

class WebSshClient {
    constructor() {
        /* WebSocket连接对象 */
        this.connection = null;
    }

    /**
     * 生成对端地址协议
     * @returns {string}
     */
    generatePeerAddress() {
        return `${window.location.protocol === 'https:' ? 'wss://' : 'ws://'}${process.env.VUE_APP_SOCKET_BASE_API || ''}`;
    }

    /**
     *
     * @param {*} obj
     * @returns
     */
    isType(obj) {
        let type = Object.prototype.toString.call(obj) || '';
        let typeSplit = type.split(' ') || ['', ' '];
        return typeSplit[1].slice(0, typeSplit[1].length - 1);
    }

    /**
     * 连接WebSocket 参数
     * @param options
     */
    connect(options) {
        return new Promise((resolve, reject) => {
            const endpoint = this.generatePeerAddress();
            if (window.WebSocket) {
                this.connection = new WebSocket(`${endpoint}${options.url}/${new Date().getTime()}`);
            } else {
                useMessage().warning('连接失败，浏览器不支持WebSocket！')
                reject('WebSocket连接失败，浏览器不支持WebSocket！');
                this.close().then(console.error);
                return;
            }
            /* 连接成功并执行回调 */
            this.connection.onopen = () => {
                options.onOpen && this.isType(options.onOpen) === 'Function' ? options.onOpen() : '';
                resolve();
            }
            /* 连接失败并执行回调 */
            this.connection.onerror = () => {
                this.connection && options.onError && this.isType(options.onError) === 'Function' ? options.onError('WebSocket连接发生错误！已断开！') : '';
                this.close().then(console.info);
                reject('WebSocket连接发生错误！');
            }
            /* 发送消息并执行回调 */
            this.connection.onmessage = (e) => {
                options.onMessage && this.isType(options.onMessage) === 'Function' ? options.onMessage(e) : '';
            }
            /* 关闭消息并执行回调 */
            this.connection.onclose = (e) => {
                if (options.onError && this.isType(options.onError) === 'Function' && e.code && e.code !== 1001) {
                    this.connection && options.onError(`错误代码：${e.code}，断开原因：${e.reason || '异常关闭'}， 是否正常断开连接：${e.wasClean}`)
                    reject('WebSocket连接发生错误！连接已关闭！');
                    this.close().then(console.info);
                    return
                }
                if (this.connection && options.onClose && this.isType(options.onClose) === 'Function') {
                    options.onClose({msg: "WebSocket连接已关闭", data: e})
                }
            }
        })
    }

    /**
     * 发送信息
     * @param data
     */
    send(data) {
        if (this.connection) {
            this.isType(data) === 'String' ? this.connection.send(data) : this.connection.send(JSON.stringify(data));
        }
    }

    /**
     * 关闭连接
     */
    close() {
        return new Promise((resolve) => {
            this.connection ? this.connection.close() : '';
            this.connection = null;
            resolve('WebSocket连接关闭');
        })
    }
}

export default new WebSshClient();
